package com.adminsystem.common.security;

import com.adminsystem.common.utils.CheckResult;
import com.adminsystem.common.utils.JWTUtil;
import com.adminsystem.common.utils.StringUtils;
import com.adminsystem.entity.SysUser;
import com.adminsystem.service.SysUserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import com.adminsystem.common.constant.JWTConstant;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private SysUserService service;

    @Autowired
    private MyUserDetailServiceImpl myUserDetailService;
    private static final String[] URL_WHITELIST = {
            "/login",
            "/logout",
            "/captcha",
            "/password",
            "/image/**",
            "/doc.html",
            "/css/**",
            "/js/**",
            "/img/**",
            "/index.html",
            "favicon.ico",
            "/doc.html",
            "/swagger-resources/**",
            "/v2/api-docs/**",
            "/ws/**",
            "/swagger-ui/**",
            "/webjars/**",
            "/druid/**",
            "/actuator/**",
            "/admin/**",
            "/imserver/**"
    };

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
//        super.doFilterInternal(request, response, chain);
        String token = request.getHeader("token");
        System.out.println("请求地址:" + request.getRequestURI());
        //如果token是空则放行
        if (StringUtils.isEmpty(token) || new ArrayList<String>(Arrays.asList(URL_WHITELIST)).contains(request.getRequestURI())) {
            chain.doFilter(request, response);
        } else {
            CheckResult checkResult = JWTUtil.validateJWT(token);
            if (!checkResult.isSuccess()) {
                switch (checkResult.getErrCode()) {
                    case JWTConstant.JWT_ERRCODE_NULL:
                        throw new JwtException("Token不存在");
                    case JWTConstant.JWT_ERRCODE_FAIL:
                        throw new JwtException("Token验证不通过");
                    case JWTConstant.JWT_ERRCODE_EXPIRE:
                        throw new JwtException("Token过期");

                }
            }
            Claims claims = JWTUtil.parseJWT(token);
            String username = claims.getSubject();
            SysUser sysUser = service.getByUserName(username);

            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(sysUser, null, myUserDetailService.getUserAuthority(sysUser.getId()));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            chain.doFilter(request, response);
        }
    }
}
